/**
 * <p>Title: CommonController.java</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2015</p>
 * <p>Company: yihaoxue</p>
 * @author victoryu
 * @date 2015年8月6日
 * @version 1.0
 */
package com.siysoft.tc.base.action;

import java.io.IOException;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.siysoft.exception.FileUploadException;
import com.siysoft.tc.base.bean.property.ResourceType;
import com.siysoft.tc.base.bean.to.Resource;
import com.siysoft.tc.base.bean.to.User;
import com.siysoft.tc.base.service.ICommonService;
import com.siysoft.tc.base.service.IUserService;
import com.siysoft.util.COMMON;
import com.siysoft.util.Md5Encrypt;
import com.siysoft.util.fileupload.FileUpload;
import com.tc.base.controller.BaseController;

/**
 * <p>
 * Title: 基础的控制器
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company: yihaoxue
 * </p>
 * 
 * @author victoryu
 * @date 2015年8月6日
 */

@Controller
@RequestMapping(value = "/app")
public class CommonController extends BaseController {
	@Autowired
	IUserService userService;
	@Autowired
	ICommonService commonService;	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/start")
	public String start(HttpServletRequest request,
			HttpServletResponse response){
			return "start";
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/register_1")
	public String register_1(HttpServletRequest request,
			HttpServletResponse response){
		
			return "register";
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/register_2")
	public String register_2(HttpServletRequest request,
			HttpServletResponse response){
		
			return "register2";
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/login_index")
	public String login_index(HttpServletRequest request,
			HttpServletResponse response){
		
			return "login";
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/start2")
	public String start2(HttpServletRequest request,
			HttpServletResponse response){
			return "start2";
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request,
			HttpServletResponse response){
			if(request.getParameter("type") != null){
				request.setAttribute("type", 1);
				request.setAttribute("user_id", request.getParameter("user_id"));
				request.setAttribute("reservation_id", request.getParameter("reservation_id"));
				request.setAttribute("user_type", request.getParameter("user_type"));
				request.setAttribute("user_name", request.getParameter("user_name"));
			}
			return "index";
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/personal")
	public String personal(HttpServletRequest request,
			HttpServletResponse response){
			if(request.getParameter("type") != null){
				request.setAttribute("type", 1);
				request.setAttribute("user_id", request.getParameter("user_id"));
				request.setAttribute("reservation_id", request.getParameter("reservation_id"));
				request.setAttribute("user_type", request.getParameter("user_type"));
				request.setAttribute("user_name", request.getParameter("user_name"));
			}
			return "personal";
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/protocol")
	public String protocol(HttpServletRequest request,
			HttpServletResponse response){
		
			return "protocol";
	}
	
	/**
	 * @category 上传或修改头像.
	 * @author victoryu
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/uploadavatar")
	public void uploadavatar(HttpServletRequest request,HttpServletResponse response) throws FileUploadException{
		String local = request.getServletContext().getRealPath("/"); 
		int user_id;
		User user;
		try{
			if(COMMON.isnull(request.getParameter("user_id")))
			{
				this.responseFail(response, 40003, "请先登录!","");
				return;
			}
			user_id=Integer.parseInt(request.getParameter("user_id").toString());
			user=userService.getUserById(user_id);
			if(user == null)
			{
				this.responseFail(response, 40001, "用户不存在","");
				return;
			}
			String user_avatar = request.getParameter("user_avatar_data");
			System.out.println("uuuuuuuuuuuuuuuuuu"+user_avatar);
			//Map<String, String> fileUpload = iCommonService.fileUpload(request, user.getUserId()+"");
			Resource resource=new Resource();
			JSONObject obj = new JSONObject();
			resource.setUserId(user.getUser_id());
			resource.setDataId(user.getUser_id());
				resource.setImgPath(new FileUpload().uploadFileByBase64(user_avatar, String.valueOf(user.getUser_id()), request));
				resource.setDataType(ResourceType.USER_AVATAR);
				obj.accumulate("avatar_url", resource.getImgPath());
			resource.setAuditFlag((byte)0); 
			resource.setUploadTime(new Timestamp(System.currentTimeMillis())); 
			userService.changehead(resource, local);
			String format_json = this.FormatJson(0,"",Object2Json(obj));
			this.responseSuccess(response,format_json,0);
			
			}catch(Exception e){
				e.printStackTrace();
				
				this.responseFail(response, -32602, "小艺有点忙哦~请稍后重试^_^","");
				return;
		}
		
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 */
	
	@RequestMapping(value = "/register1")
	public String register1(HttpServletRequest request,
			HttpServletResponse response){
		try{
			if( COMMON.isnull(request.getParameter("name"))
					|| COMMON.isnull(request.getParameter("telephone"))
					|| COMMON.isnull(request.getParameter("email"))
					|| COMMON.isnull(request.getParameter("password"))
					)
			{
				this.responseFail(response, -32602, "参数无效", "指定参数不符合服务接口定义");
			}
			String name = request.getParameter("name").toString();
			String telephone = request.getParameter("telephone").toString();
			String email = request.getParameter("email").toString();
			String password = request.getParameter("password").toString();
			String grade = request.getParameter("grade");
			password = Md5Encrypt.md5(password);
			
			User user = userService.createUser(name, telephone, email, password, grade);
			
			/*JSONObject obj = new JSONObject();
			obj.accumulate("result", result);
			String format_json = this.FormatJson(0, "", Object2Json(obj));
			this.responseSuccess(response, format_json, 0);*/
			System.out.println("***********************************************user:" + user);
			if(!COMMON.isnull(user)){
				System.out.println("***********************************************1111111:" + 111111);
				boolean sendResult = false;
				if (email.matches("^[0-9a-z][a-z0-9\\._-]{1,}@[a-z0-9-]{1,}[a-z0-9]\\.[a-z\\.]{1,}[a-z]$")) {
					//发送邮箱信息
					try{
					sendResult=commonService.sendEmailMsg(email,COMMON.getIpAddress(request),"[tc]welcome to tc_platfrom","注册成功!欢迎常来tc,提升技能值!");
					sendResult=true;
					}
					catch (Exception e) {
						e.printStackTrace();
						sendResult = false;
						COMMON.error(e.getMessage());
					}
				}
				System.out.println("***********************************************sendResult:" + sendResult);
				System.out.println("***********************************************email:" + email);
				//发送成功时
				request.getSession().setAttribute("user", user);
				return "forward:register_2.htm";
			}
			else
			{
				request.setAttribute("msg", "用户名或电话或邮箱已经被使用了");
				return "error";
			}
				
		}
		catch(Exception e){
			e.printStackTrace();
			request.setAttribute("msg", "服务器有点忙，请过会重试");
			return "error";
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 */
	
	@RequestMapping(value = "/judgename")
	public void judgename(HttpServletRequest request,
			HttpServletResponse response){
		try{
			if( COMMON.isnull(request.getParameter("name"))
					)
			{
				this.responseFail(response, -32602, "参数无效", "指定参数不符合服务接口定义");
			}
			String name = request.getParameter("name").toString();
			
			Integer result = userService.judgeName(name);
			
			JSONObject obj = new JSONObject();
			obj.accumulate("result", result);
			String format_json = this.FormatJson(0, "", Object2Json(obj));
			this.responseSuccess(response, format_json, 0);
			return;
		}
		catch(Exception e){
			e.printStackTrace();
			this.responseFail(response, -32602, "服务器有点忙，请过会重试", "");
			return ;
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 */
	
	@RequestMapping(value = "/judgelecture")
	public void judgelecture(HttpServletRequest request,
			HttpServletResponse response){
		try{
			if( COMMON.isnull(request.getParameter("name"))
					)
			{
				this.responseFail(response, -32602, "参数无效", "指定参数不符合服务接口定义");
			}
			String name = request.getParameter("name").toString();
			
			Integer result = userService.judgeLecture(name);
			
			JSONObject obj = new JSONObject();
			obj.accumulate("result", result);
			String format_json = this.FormatJson(0, "", Object2Json(obj));
			this.responseSuccess(response, format_json, 0);
			return;
		}
		catch(Exception e){
			e.printStackTrace();
			this.responseFail(response, -32602, "服务器有点忙，请过会重试", "");
			return ;
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 */
	
	@RequestMapping(value = "/judgetelephone")
	public void judgetelephone(HttpServletRequest request,
			HttpServletResponse response){
		try{
			if( COMMON.isnull(request.getParameter("telephone"))
					)
			{
				this.responseFail(response, -32602, "参数无效", "指定参数不符合服务接口定义");
			}
			String telephone = request.getParameter("telephone").toString();
			
			Integer result = userService.judgeTelephone(telephone);
			
			JSONObject obj = new JSONObject();
			obj.accumulate("result", result);
			String format_json = this.FormatJson(0, "", Object2Json(obj));
			this.responseSuccess(response, format_json, 0);
			return;
		}
		catch(Exception e){
			e.printStackTrace();
			this.responseFail(response, -32602, "服务器有点忙，请过会重试", "");
			return ;
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 */
	
	@RequestMapping(value = "/judgeemail")
	public void judgeemail(HttpServletRequest request,
			HttpServletResponse response){
		try{
			if( COMMON.isnull(request.getParameter("email"))
					)
			{
				this.responseFail(response, -32602, "参数无效", "指定参数不符合服务接口定义");
			}
			String email = request.getParameter("email").toString();
			
			Integer result = userService.judgeEmail(email);
			
			JSONObject obj = new JSONObject();
			obj.accumulate("result", result);
			String format_json = this.FormatJson(0, "", Object2Json(obj));
			this.responseSuccess(response, format_json, 0);
			return;
		}
		catch(Exception e){
			e.printStackTrace();
			this.responseFail(response, -32602, "服务器有点忙，请过会重试", "");
			return ;
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 */
	
	@RequestMapping(value = "/register2")
	public String register2(HttpServletRequest request,
			HttpServletResponse response){
		try{
			if( COMMON.isnull(request.getParameter("id"))
					|| COMMON.isnull(request.getParameter("interest"))
					|| COMMON.isnull(request.getParameter("school"))
					|| COMMON.isnull(request.getParameter("student_id"))
					)
			{
				this.responseFail(response, -32602, "参数无效", "指定参数不符合服务接口定义");
			}
			Integer id = Integer.valueOf(request.getParameter("id").toString());
			String interest_str = request.getParameter("interest").toString();
			JSONArray interest = JSONArray.fromObject(interest_str);
			String school = request.getParameter("school").toString();
			String student_id = request.getParameter("student_id").toString();
			
			Integer result = userService.completeUser(id, school, student_id);
			Integer result2 = userService.setInterest(id, interest);
			
			/*JSONObject obj = new JSONObject();
			obj.accumulate("result", result);
			String format_json = this.FormatJson(0, "", Object2Json(obj));
			this.responseSuccess(response, format_json, 0);*/
			return "forward:login_index.htm";
		}
		catch(Exception e){
			e.printStackTrace();
			this.responseFail(response, -32602, "服务器有点忙，请过会重试", "");
			return "error";
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 */
	
	@RequestMapping(value = "/login")
	public String login(HttpServletRequest request,
			HttpServletResponse response){
		try{
			if( COMMON.isnull(request.getParameter("name_email_studentid"))
					|| COMMON.isnull(request.getParameter("password"))
					)
			{
				//this.responseFail(response, -32602, "参数无效", "指定参数不符合服务接口定义");
				return "login";
			}
			String name_email_studentid = request.getParameter("name_email_studentid").toString();
			String password = request.getParameter("password").toString();
			password = Md5Encrypt.md5(password);
			
			User user = userService.login(name_email_studentid);
			
			if(user == null){
				this.responseFail(response, 40001, "用户不存在", "");
				request.setAttribute("msg", "用户不存在");
				return "login";
			}
			else if(!user.getUser_password().equals(password)){
				this.responseFail(response, 40004, "密码错误", "");
				request.setAttribute("msg", "密码错误");
				return "login";
			}else if(user.getUser_lock().equals(1)){
				this.responseFail(response, 40004, "用户已经被冻结", "");
				request.setAttribute("msg", "用户已经被冻结，请联系管理员");
				return "login";
			}
			request.getSession().setAttribute("user", user);
			/*JSONObject obj = new JSONObject();
			obj.accumulate("result", 1);
			String format_json = this.FormatJson(0, "", Object2Json(obj));
			this.responseSuccess(response, format_json, 0);*/
			return "forward:index.htm";
		}
		catch(Exception e){
			e.printStackTrace();
			this.responseFail(response, -32602, "服务器有点忙，请过会重试", "");
			return "error";
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 */
	
	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request,
			HttpServletResponse response){
		try{	
			request.getSession().removeAttribute("user");
			return "login";
		}
		catch(Exception e){
			e.printStackTrace();
			this.responseFail(response, -32602, "服务器有点忙，请过会重试", "");
			return "error";
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	
	@RequestMapping(value = "/test_session")
	public String test_session(HttpServletRequest request,
			HttpServletResponse response) throws IOException{		
			HttpSession session = request.getSession();
			//将数据存储到session中
			session.setAttribute("data", "孤傲苍狼");
			//获取session的Id
			String sessionId = session.getId();
			//判断session是不是新创建的
			if (session.isNew()) {
				response.getWriter().print("session创建成功，session的id是："+sessionId);
			}else {
			    response.getWriter().print("服务器已经存在该session了，session的id是："+sessionId);
			}
			return null;
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	
	@RequestMapping(value = "/get_session")
	public String get_session(HttpServletRequest request,
			HttpServletResponse response) throws IOException{		
			HttpSession session = request.getSession();
			User user = (User)session.getAttribute("user");
			response.getWriter().print(user.getUser_id());
			return null;
	}
}
